angular.module('blog.service',['ionic','ngSanitize'])
.constant('jconfig',{
     api_base:"http://jaylabs.sinaapp.com/Api/",
})
.config(function($httpProvider,$provide){
    //对php的post处理
    $httpProvider.defaults.transformRequest = function(request){
     if(typeof(request)!='object')
     {
            return request;
     }
     var str = [];
     for(var k in request){
        if(k.charAt(0)=='$'){
                delete request[k];
                 continue;
        }
       var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
       str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
     }
     return str.join("&");
   };
   $httpProvider.defaults.timeout=10000;
   $httpProvider.defaults.headers.post = {
        'Content-Type': 'application/x-www-form-urlencoded'
   };
   $httpProvider.responseInterceptors.push('interceptor');

})
.factory('interceptor',function($q,jconfig,$injector){
    return function(promise)
    {
       return promise.then(function(response){
            if('object'!=typeof(response.data))
            {
                if(0===response.config.url.indexOf(jconfig.api_base))
                {
                    //如果请求接口返回的内容不是json数据，则报错
                    alert('服务出错，请稍后再试!');
                    console.log(response);
                    return $q.reject({code:-3,messge:"response format error"});
                }
                return response;
            }
            //去除错误码，只返回数据部分
            if('undefined'!=typeof(response.data.data))
            {
                response.data=response.data;
            }
            return response;
        },function(response){
            alert('服务器端出错');
            response.data={
               code:-6,
               message:response
            };
           return $q.reject(response);
        });
    };
})
//JobDeer 工具
.factory('$jd',function($http,jconfig,$timeout,$location){
    return {
        apiurl:function(url){
            /*
            if(-1==url.indexOf('?'))
            {
                url+="?app_key="+jconfig.app_key;
            }
            else
            {
                url+="&app_key="+jconfig.app_key;
            }
            */
            return jconfig.api_base+url;
        },
        get:function(url){
            url = this.apiurl(url);
            return $http.get(url);
        },
        post:function(url,param){
            url=this.apiurl(url);
            return $http.post(url,param);
        },
        //监听请求条件的变化，可以间隔自动刷新列表
        watch:function(scope,timeout,change_search)
        {
            if('undefined'==typeof(change_search))
            {
                //是否改变url的querystring
                change_search=false;
            }
            var success_cb=function(data){};
            var error_cb=function(data){};
            var cb={
                success:function(func){
                    //设置成功的回调函数
                    success_cb=func;
                    return cb;
                },
                error:function(func){
                    //设置失败的回调函数
                    error_cb=func;
                    return cb;
                },
                reload:function(){
                    run();
                }
            };

            if(!scope.request)
            {
                alert('watch 方法没有指定scope.request');
                return ;
            }

            if(!scope.request.url)
            {
                alert('watch 方法没有指定scope.request.url');
                return ;
            }

            if(!scope.request.params)
            {
                 scope.request.params={};
            }

            scope.request.reload=function(){
                run();
            };

            var self=this;
            var run=function()
            {
                 var url=self.apiurl(scope.request.url);
                 if(url.indexOf('?')==-1)
                 {
                    url+='?'+$.param(scope.request.params)
                 }
                 else
                 {
                    url+='&'+$.param(scope.request.params)
                 }
                 $http.get(url).success(success_cb).error(error_cb);
                 if(change_search)
                 {
                     $location.search(scope.request.params);
                 }
            };
            scope.$watch('request',run,true);

            if(timeout)
            {
                timeout = timeout*1000;
                //如果设置了timeout，会实时刷新
                cancelRefresh = $timeout(function myFunction() {
                    run();
                    cancelRefresh = $timeout(myFunction, timeout);
                },timeout);

                //切换到其他页面后，终止自动刷新
                scope.$on('$destroy', function(e) {
                            $timeout.cancel(cancelRefresh);
                });
            }
            return cb;
        }
    };
})
.filter('default',function(){
        return function(data,default_value){
            return data?data:default_value;
        };
})
.filter('undefined',function(){
    return function(data){
        return 'undefined'==typeof(data);
    };
})

.filter('empty',function(){
    return function(data){
        if('undefined'==typeof(data))
        {
            return false;
        }
        return data?false:true;
    };
})

.filter('unsafe', ['$sce', function ($sce) {
        return function (val) {
            return $sce.trustAsHtml(val);
        };
}])

.filter('jdate',function($filter){
    return function(date,format){
        var arr = date.split(/[- :]/),
        time = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
        //转换字符串为时间戳再格式化
        //为什么不用 Date.parse(str) 直接转换字符串为时间戳,  因为 Date.parse 支持的字符串时间格式有限，容易返回NaN
       return $filter('date')(time.getTime(), format);
    };
})
.directive('jpage',function(){
    return {
        restrict:"EA",
        replace:true,
        template:'<ul class="pagination" ng-if="show"><li ng-click="go({page:1})"><a href="javascript:void(0);" title="首页">&laquo;</a></li><li ng-repeat="page in pages"  ng-class="{active:page==currentpage}"  ng-click="go({page:page})"><a href="javascript:void(0);">{{page}}</a></li><li ng-click="go({page:totalpage})"><a href="javascript:void(0);" title="尾页">&raquo;</a></li></ul>',
        scope:{
            //总页数
            totalpage:"=",
            //当前页数
            currentpage:"=",
            //显示分页个数,默认为10
            size:"=",
            //分页回调函数,传递参数page
            go:"&"
        },
        controller:function($scope,$element,$attrs,$transclude){
            var run=function(){
                var totalpage=parseInt($scope.totalpage);
                //要有两页才显示分页
                $scope.show=totalpage>1?true:false;
                if(!$scope.show)
                    return ;
                var currentpage=parseInt($scope.currentpage);
                var size=$scope.size?parseInt(size):10;
                var half_size=parseInt((size+1)/2);
                var start_page=currentpage-half_size;
                if(start_page<1)
                {
                    half_size+=Math.abs(start_page);
                    start_page=1;
                }
                var end_page=currentpage+half_size;
                if(end_page>totalpage)
                {
                    var start_page=start_page-(end_page-totalpage);
                    if(start_page<1)
                        start_page=1;
                    end_page=totalpage;
                }
                var pages=[];
                for(i=start_page;i<=end_page;i++)
                {
                    pages.push(i);
                }
                $scope.pages=pages;
                $scope.totalpage=totalpage;
                $scope.currentpage=currentpage;
            };
            $scope.$watch('totalpage+currentpage',function(){
                //计算更改pages变量
                run();
            });
        }
    };
})

.factory('jalert',function($ionicPopup){
    return function(message,title,cb){
            if('function'==typeof(title))
            {
                //第二个参数可以是回调函数，也可以是标题
                cb=title;
                title=false;
            }
            title= title || '系统消息';
            $ionicPopup.alert({
                  title: title,
                  content: message,
                  okText: "知道了",
                  okType: "jd-alert-btn"
            }).then(function(){
                if(cb)
                {
                    cb();
                }
            });
    }
})
.factory('jconfirm',function($ionicPopup){
    return function(message,title,cb)
    {
        if('function'==typeof(title))
        {
            //第二个参数可以是回调函数，也可以是标题
            cb=title;
            title=false;
        }
        title= title || '系统消息';
        $ionicPopup.confirm({
              title: title,
              content: message,
              cancelText: '取消',
              cancelType: 'jd-cancel-btn',
              okText: '确定',
              okType: 'jd-alert-btn'

        }).then(function(ret){
            if(cb)
            {
                cb(ret);
            }
        });
    }
})
//指定后退地址
.factory('jdBack',function($state,$ionicPlatform){
    return function(url)
    {
        var jdback=function(e){
            $state.go(url);
            deregisterBackbutton();
            e.preventDefault();
            return false;
        };
        var deregisterBackbutton=$ionicPlatform.registerBackButtonAction(
            jdback,
            120
        );
    };
})
//退出二次确认
.factory('jdExitConfirm',function($rootScope,jconfirm,$ionicPlatform,$ionicViewService){
    return function(){
        var jdconfirm=function(e)
        {
           e.preventDefault();
           deregisterBackbutton();
            if($rootScope.$viewHistory.backView) {
                $rootScope.$viewHistory.backView.go();
            }else{
                jconfirm('是否确认退出',function(ret){
                    if(ret)
                    {
                        navigator.app.exitApp();
                    }
                    else
                    {
                        //如果用户取消，再重新监听后退
                     deregisterBackbutton=$ionicPlatform.registerBackButtonAction(
                            jdconfirm,
                            101
                         );
                    }
                });
            }
            return false;
        };
        var deregisterBackbutton=$ionicPlatform.registerBackButtonAction(
            jdconfirm,
            101
        );
    };
})
;
